package com.atu.rtc.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;

/**
 * 获取设备指纹的工具类
 *
 * @author BarryHuang
 * @DATE 2015-8-19
 */

public class FingerprintUtil {
    private static final String TAG = FingerprintUtil.class.getSimpleName();


    /**
     * 生成一个设备指纹（耗时50毫秒以内）：
     * 1.IMEI + 设备硬件信息（主要）+ ANDROID_ID + WIFI MAC组合成的字符串
     * 2.用MessageDigest将以上字符串处理成32位的16进制字符串
     *
     * @param pwd
     * @return 设备指纹
     */
    public static String createFingerprint(String pwd) {

        // 创建一个 messageDigest 实例
//        MessageDigest msgDigest = null;
//        try {
//            msgDigest = MessageDigest.getInstance("sha-256");
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        }
//
//        //用 MessageDigest 将 deviceId 处理成32位的16进制字符串
//        msgDigest.update(pwd.getBytes(), 0, pwd.length());
//        // get md5 bytes
//        byte md5ArrayData[] = msgDigest.digest();
//
//        // create a hex string
//        String deviceUniqueId = new String();
//        for (int i = 0; i < md5ArrayData.length; i++) {
//            int b = (0xFF & md5ArrayData[i]);
//            // if it is a single digit, make sure it have 0 in front (proper
//            // padding)
//            if (b <= 0xF) deviceUniqueId += "0";
//            // add number to string
//            deviceUniqueId += Integer.toHexString(b);
////          Log.i(TAG,"deviceUniqueId=" + deviceUniqueId);
//        } // hex string to uppercase
//        deviceUniqueId = deviceUniqueId.toUpperCase();
//        Log.d(TAG, "生成的设备指纹：" + deviceUniqueId);
//
//        return deviceUniqueId;

        try {
            byte[] cert = pwd.getBytes();
            MessageDigest md = MessageDigest.getInstance("SHA256");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length() - 1);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}